package io.terminus.lego.shinda.web.security.oauth

import org.springframework.security.oauth2.client.registration.ClientRegistration
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository
import org.springframework.util.Assert

/**
 * 自定义Client注册仓库（第三方账户登录UC）
 * @author wangmeng
 * @date 2018/4/21
 */
class CustomClientRegistrationRepository : ClientRegistrationRepository, Iterable<ClientRegistration> {
    private val registrations: Map<String, ClientRegistration>

    /**
     * Constructs an `InMemoryClientRegistrationRepository` using the provided parameters.

     * @param registrations the client registration(s)
     */
    constructor(registrations: List<ClientRegistration>) {
        Assert.notEmpty(registrations, "registrations cannot be empty")
        registrations.toMutableList().map { it.registrationId to it }.toMap()
        this.registrations = registrations.toMutableList().associateBy { it.registrationId }
    }

    override fun findByRegistrationId(registrationId: String): ClientRegistration? {
        Assert.hasText(registrationId, "registrationId cannot be empty")
        return this.registrations[registrationId]
    }

    /**
     * Returns an `Iterator` of [ClientRegistration].

     * @return an `Iterator<ClientRegistration>`
     */
    override fun iterator(): Iterator<ClientRegistration> {
        return this.registrations.values.iterator()
    }
}